import time
import base64
from flask import Blueprint, request, jsonify, current_app
import dashscope
from dashscope import MultiModalConversation
from datetime import datetime
from app.utils.mongo import db
import requests
import os
from flask_jwt_extended import jwt_required, get_jwt_identity
from bson.objectid import ObjectId

# 创建蓝图
image_recognition_bp = Blueprint('image_recognition', __name__, url_prefix='/api')

# 获取图片识别集合 - 使用正确的集合名称
image_records_collection = db['building_records']  # 变更集合名称

@image_recognition_bp.route('/building/identify', methods=['POST'])
@jwt_required()  # 添加身份验证
def identify_building():
    """建筑识别接口（关联用户）"""
    start_time = time.time()
    
    # 获取当前用户ID
    current_user_id = get_jwt_identity()
    
    # 在这里设置 API Key，确保在应用上下文中
    dashscope.api_key = current_app.config['DASHSCOPE_API_KEY']
    
    data = request.json
    image_url = data.get('imageUrl')
    description = data.get('description', '')  # 获取图片描述
    
    if not image_url:
        return jsonify({
            "code": -1,
            "msg": "缺少图片URL参数"
        }), 400
    
    try:
        # 下载图片并转换为base64
        try:
            # 处理URL - 如果是相对路径，补充完整域名
            if image_url.startswith('/'):
                base_url = f"http://{request.host}"
                full_image_url = f"{base_url}{image_url}"
                current_app.logger.info(f"转换相对路径为完整URL: {full_image_url}")
            else:
                full_image_url = image_url
            
            # 增加请求头，模拟浏览器请求
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
            img_response = requests.get(full_image_url, timeout=10, headers=headers, stream=True)
            img_response.raise_for_status()
            
            # 将图片转换为base64
            image_data = img_response.content
            base64_image = base64.b64encode(image_data).decode('utf-8')
            
        except requests.RequestException as e:
            current_app.logger.error(f"图片下载失败: {str(e)}, URL: {full_image_url}")
            return jsonify({
                "code": -1,
                "msg": "图片下载失败，请重新上传"
            }), 400
        
        # 调用通义千问VL-Plus模型识别建筑，使用base64格式
        messages = [
            {
                "role": "user",
                "content": [
                    {"image": f"data:image/jpeg;base64,{base64_image}"},
                    {"text": "这是什么客家建筑？请提供名称和详细描述，如果无法识别，请明确说明"}
                ]
            }
        ]
        
        # 设置模型调用超时（延长至60秒避免超时）
        response = MultiModalConversation.call(
            model='qwen-vl-plus',
            messages=messages,
            timeout=60  # 延长超时时间
        )
        
        processing_time = time.time() - start_time
        current_app.logger.info(f"识别处理时间: {processing_time:.2f}秒")
        
        if response.status_code == 200:
            answer = response.output.choices[0].message.content
            
            # 尝试从回答中提取建筑名称和描述
            building_name = "未知建筑"
            building_desc = answer
            building_type = ""  # 新增：建筑类型
            
            # 更健壮的解析逻辑
            if isinstance(answer, list) and len(answer) > 0 and "text" in answer[0]:
                text_content = answer[0]["text"]
                # 尝试提取建筑名称（假设第一行是名称）
                lines = text_content.split('\n')
                if len(lines) > 0:
                    building_name = lines[0].strip()
                    # 剩余部分作为描述
                    building_desc = '\n'.join(lines[1:]) if len(lines) > 1 else text_content
            elif isinstance(answer, str):
                lines = answer.split('\n')
                if len(lines) > 0:
                    building_name = lines[0].strip()
                    building_desc = '\n'.join(lines[1:]) if len(lines) > 1 else answer
            
            # 更健壮的建筑类型提取逻辑
            name_lower = building_name.lower()
            # 增加模糊匹配，处理可能的别名或变体
            if any(keyword in name_lower for keyword in ["圆形土楼", "土楼", "圆形围楼"]):
                building_type = "round_tulou"
            elif any(keyword in name_lower for keyword in ["方形土楼", "土楼", "方形围楼"]):
                building_type = "square_tulou"
            elif any(keyword in name_lower for keyword in ["围龙屋", "围龙", "龙屋"]):
                building_type = "weilong_house"
            elif any(keyword in name_lower for keyword in ["四角楼", "四角围楼", "四角土楼"]):
                building_type = "four_corner_building"
            else:
                building_type = "unknown"
            
            # 存储到MongoDB
            record = {
                "user_id": ObjectId(current_user_id),  # 添加用户关联
                "image_url": image_url,
                "question": "这是什么客家建筑？",
                "answer": answer,
                "result": {
                    "name": building_name,
                    "description": building_desc,
                    "type": building_type  # 存储建筑类型
                },
                "is_saved": False,  # 默认未保存
                "tokens_used": response.usage,
                "processing_time": processing_time,
                "created_at": datetime.utcnow(),
                "updated_at": datetime.utcnow()
            }

            result = image_records_collection.insert_one(record)
            
            return jsonify({
                "code": 0,
                "msg": "识别成功",
                "data": {
                    "record_id": str(result.inserted_id),  # 返回记录ID
                    "id": str(record["_id"]),
                    "name": building_name,
                    "description": building_desc,
                    "type": building_type  # 新增：返回建筑类型
                }
            })
        else:
            current_app.logger.error(f"模型调用失败: {response.message}")
            return jsonify({
                "code": -1,
                "msg": f"识别失败: {response.message}"
            }), 500
            
    except Exception as e:
        processing_time = time.time() - start_time
        current_app.logger.error(f"图片识别错误: {str(e)}, 处理时间: {processing_time:.2f}秒")
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}"
        }), 500

@image_recognition_bp.route('/records/save/<record_id>', methods=['POST'])
@jwt_required()
def save_record(record_id):
    """保存识别记录"""
    user_id = get_jwt_identity()
    
    try:
        result = image_records_collection.update_one(
            {"_id": ObjectId(record_id), "user_id": ObjectId(user_id)},
            {"$set": {"is_saved": True, "updated_at": datetime.utcnow()}}
        )
        
        if result.modified_count > 0:
            return jsonify({
                "code": 0,
                "msg": "记录保存成功"
            })
        return jsonify({
            "code": -1,
            "msg": "记录不存在或无权操作"
        }), 403
        
    except Exception as e:
        current_app.logger.error(f"保存记录错误: {str(e)}")
        return jsonify({
            "code": -1,
            "msg": "保存失败"
        }), 500

@image_recognition_bp.route('/records/unsave/<record_id>', methods=['POST'])
@jwt_required()
def unsave_record(record_id):
    """取消保存识别记录"""
    user_id = get_jwt_identity()
    
    try:
        result = image_records_collection.update_one(
            {"_id": ObjectId(record_id), "user_id": ObjectId(user_id)},
            {"$set": {"is_saved": False, "updated_at": datetime.utcnow()}}
        )
        
        if result.modified_count > 0:
            return jsonify({
                "code": 0,
                "msg": "取消保存成功"
            })
        return jsonify({
            "code": -1,
            "msg": "记录不存在或无权操作"
        }), 403
        
    except Exception as e:
        current_app.logger.error(f"取消保存记录错误: {str(e)}")
        return jsonify({
            "code": -1,
            "msg": "操作失败"
        }), 500

@image_recognition_bp.route('/records', methods=['GET'])
@jwt_required()
def get_user_records():
    """获取用户的识别记录"""
    user_id = get_jwt_identity()
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 10))
    skip = (page - 1) * limit
    saved_only = request.args.get('saved_only', 'false').lower() == 'true'
    
    query = {"user_id": ObjectId(user_id)}
    if saved_only:
        query["is_saved"] = True
    
    try:
        records = list(image_records_collection.find(
            query,
            {"_id": 1, "image_url": 1, "result": 1, "is_saved": 1, "created_at": 1}
        ).sort("created_at", -1).skip(skip).limit(limit))
        
        total = image_records_collection.count_documents(query)
        
        # 格式化数据
        formatted_records = []
        for record in records:
            formatted_records.append({
                "id": str(record["_id"]),
                "image_url": record["image_url"],
                "building_name": record["result"]["name"],
                "building_description": record["result"]["description"],
                "saved": record["is_saved"],
                "created_at": record["created_at"].strftime("%Y-%m-%d %H:%M")
            })
            
        return jsonify({
            "code": 0,
            "data": {
                "records": formatted_records,
                "total": total,
                "page": page,
                "limit": limit
            }
        })
        
    except Exception as e:
        current_app.logger.error(f"获取记录错误: {str(e)}")
        return jsonify({
            "code": -1,
            "msg": "获取记录失败"
        }), 500

@image_recognition_bp.route('/admin/records', methods=['GET'])
@jwt_required()
def get_all_records():
    """管理员获取所有用户的识别记录"""
    # 验证管理员权限（需要在用户模型中添加role字段）
    user_id = get_jwt_identity()
    user = db['users'].find_one({"_id": ObjectId(user_id)})
    
    if not user or user.get('role') != 'admin':
        return jsonify({
            "code": -1,
            "msg": "无权访问"
        }), 403
        
    # 分页查询所有记录
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 20))
    skip = (page - 1) * limit
    
    records = list(db['building_records'].aggregate([
        {
            "$lookup": {
                "from": "users",
                "localField": "user_id",
                "foreignField": "_id",
                "as": "user_info"
            }
        },
        {"$unwind": "$user_info"},
        {"$sort": {"created_at": -1}},
        {"$skip": skip},
        {"$limit": limit}
    ]))
    
    total = db['building_records'].count_documents({})
    
    # 格式化管理员视图数据
    formatted_records = []
    for record in records:
        formatted_records.append({
            "id": str(record["_id"]),
            "user_id": str(record["user_id"]),
            "user_nickname": record["user_info"].get("nickname", "未知用户"),
            "user_avatar": record["user_info"].get("avatar_url", ""),
            "image_url": record["image_url"],
            "building_name": record["result"]["name"],
            "saved": record["is_saved"],
            "created_at": record["created_at"].strftime("%Y-%m-%d %H:%M")
        })
    
    return jsonify({
        "code": 0,
        "data": {
            "records": formatted_records,
            "total": total,
            "page": page,
            "limit": limit
        }
    })